package com.ncmmall.mall.controller.business.banner;

import com.ncmmall.application.business.merchant.banner.BannerApplication;
import com.feijin.commons.webs.Webs;
import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.channel.GoodsChannel;
import com.ncmmall.domain.business.goods.channel.QGoodsChannel;
import com.ncmmall.domain.business.merchant.banner.MerchantBanner;
import com.ncmmall.domain.business.merchant.banner.QMerchantBanner;
import com.ncmmall.mall.controller.securitys.shiro.Securitys;
import com.ncmmall.mall.params.PageParams;
import com.ncmmall.querychannel.QueryPage;
import com.ncmmall.querychannel.QueryPageRequest;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author linxs
 * @Description: 店铺海报图
 * @Date: 2019-11-14 14:52
 */
@Controller
@RequestMapping(value = "/merchant/banner")
public class BannerController {


    private final static Logger logger = LoggerFactory.getLogger(BannerController.class);

    @Autowired
    private QueryChannelService queryChannelService;

    @Autowired
    private BannerApplication bannerApplication;


    @Value("${web.domain}")
    private String webDomain;


    /**
     * 店铺海报图列表
     *
     * @param model
     * @param pageParams
     * @param banner
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    private String list(Model model, PageParams pageParams, MerchantBanner banner) {
        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());
        String hql = builderSQL("select u from MerchantBanner u where u.merchant.id = :id ", params, banner);
        QueryPage<MerchantBanner> page = queryChannelService.findPage(hql, pageRequest.setParams(params), MerchantBanner.class);

        model.addAttribute("page", page).addAttribute("params", banner);

        return "merchant/banner/list";
    }

    /**
     * 
     * @param model
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(Model model) {
        model.addAttribute("_method", "POST");
        model.addAttribute("banner", new MerchantBanner());
        return "merchant/banner/form";
    }


    /**
     * 创建广告
     *
     * @param requestWith
     * @param advertis
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> create(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantBanner banner) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            banner.setMerchant(Securitys.currentUser());
            bannerApplication.create(banner);

            return ImmutableMap.of("status", true, "message", "创建成功");

        } catch (IllegalArgumentException e) {

            return ImmutableMap.of("status", false, "message", e.getMessage());

        } catch (Exception e) {

            logger.error("广告创建异常", e);
            return ImmutableMap.of("status", false, "message", "创建异常");

        }
    }

    /**
     * 选择商品页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/choose", method = RequestMethod.GET)
    public String choose(Model model, PageParams pageParams, Goods goods) {

        QueryPageRequest pageRequest = new QueryPageRequest().setPageNo(pageParams.getPageNo());
        Map<String, Object> params = Maps.newHashMap();
        params.put("id", Securitys.currentUser().getId());
        String hql = builderGoodsSQL("select u from Goods u where u.merchant.id = :id ", params, goods);
        QueryPage<Goods> page = queryChannelService.findPage(hql, pageRequest.setParams(params), Goods.class);

        model.addAttribute("page", page).addAttribute("params", goods);

        return "merchant/banner/choose";
    }

    private String builderGoodsSQL(String sql, Map<String, Object> params, Goods goods) {

        if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getId() > 0) {
            goods.setGoodsChannel(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getId() > 0) {
            goods.getGoodsChannel().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getId());

        } else if (null != goods.getGoodsChannel() && goods.getGoodsChannel().getParent().getParent().getId() > 0) {
            goods.getGoodsChannel().getParent().setParent(queryChannelService.findOne(QGoodsChannel.goodsChannel.id.eq(goods.getGoodsChannel().getParent().getParent().getId()), GoodsChannel.class));

            sql += " and u.goodsChannel.parent.parent.id = :cid ";
            params.put("cid", goods.getGoodsChannel().getParent().getParent().getId());
        }

        if (goods.getStatus() > 0) {
            sql += " and u.status = :status ";
            params.put("status", goods.getStatus());
        } else {
            sql += " and u.status in (3,6) ";
        }

        if (!Strings.isNullOrEmpty(goods.getGoodsNo())) {
            sql += " and u.goodsNo like :goodsno ";
            params.put("goodsno", "%" + goods.getGoodsNo() + "%");
        }

        if (!Strings.isNullOrEmpty(goods.getName())) {
            sql += " and u.name like :name ";
            params.put("name", "%" + goods.getName() + "%");
        }


        if (!Strings.isNullOrEmpty(goods.getOrderByCreateTime())) {
            sql += " order by u.createTime " + goods.getOrderByCreateTime();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByPrice())) {
            sql += " order by u.defaultPrice " + goods.getOrderByPrice();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderByStore())) {
            sql += " order by u.store " + goods.getOrderByStore();
        }

        if (!Strings.isNullOrEmpty(goods.getOrderBySalesVolume())) {
            sql += " order by u.salesVolume " + goods.getOrderBySalesVolume();
        }

        return sql;
    }


    /**
     * 编辑广告
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.GET)
    public String create(Model model, long id) {
        MerchantBanner banner = queryChannelService.findOne(QMerchantBanner.merchantBanner.id.eq(id), MerchantBanner.class);
        model.addAttribute("banner", banner);
        model.addAttribute("_method", "PUT");
        return "merchant/banner/form";
    }


    /**
     * 编辑广告
     *
     * @param requestWith
     * @param advertis
     * @return
     */
    @RequestMapping(value = "/modify", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> modify(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantBanner banner) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }


            bannerApplication.modify(banner);

            return ImmutableMap.of("status", true, "message", "编辑成功");

        } catch (IllegalArgumentException e) {

            return ImmutableMap.of("status", false, "message", e.getMessage());

        } catch (Exception e) {

            logger.error("广告编辑异常", e);
            return ImmutableMap.of("status", false, "message", "编辑异常");

        }
    }

    /**
     * 下架广告
     *
     * @param requestWith
     * @param advertis
     * @return
     */
    @RequestMapping(value = "/disable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> disable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantBanner banner) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            bannerApplication.disable(banner.getId());

            return ImmutableMap.of("status", true, "message", "下架成功");

        } catch (Exception e) {

            logger.error("广告下架异常", e);
            return ImmutableMap.of("status", false, "message", "下架异常");

        }
    }



    /**
     * 上架广告
     *
     * @param requestWith
     * @param advertis
     * @return
     */
    @RequestMapping(value = "/enable", method = RequestMethod.PUT)
    @ResponseBody
    public Map<String, Object> enable(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantBanner banner) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            bannerApplication.enabled(banner.getId());
            return ImmutableMap.of("status", true, "message", "上架成功");

        } catch (Exception e) {

            logger.error("广告上架异常", e);
            return ImmutableMap.of("status", false, "message", "上架异常");

        }
    }


    /**
     * 删除广告
     *
     * @param requestWith
     * @param advertis
     * @return
     */
    @RequestMapping(value = "/remove", method = RequestMethod.DELETE)
    @ResponseBody
    public Map<String, Object> remove(HttpServletRequest request, @RequestHeader("X-Requested-With") String requestWith, MerchantBanner banner) {
        try {
            if (!Webs.isAjaxRequest(requestWith)) {
                throw new IllegalArgumentException("request must be ajax");
            }

            bannerApplication.remove(banner.getId());
            return ImmutableMap.of("status", true, "message", "删除成功");

        } catch (Exception e) {

            logger.error("广告删除异常", e);
            return ImmutableMap.of("status", false, "message", "删除异常");

        }
    }

    private String builderSQL(String sql, Map<String, Object> params, MerchantBanner banner) {

        if (StringUtils.isNotBlank(banner.getName())) {
            sql += " and name like :name";
            params.put("name", "%" + banner.getName() + "%");
        }

        if (banner.getStatus() > 0) {
            sql += " and status = :status";
            params.put("status", banner.getStatus());
        }

        sql += " order by rank asc ";

        return sql;
    }

}
